package me.sealer.ssm.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import me.sealer.ssm.constant.Dict;
import me.sealer.ssm.constant.PageConstant;
import me.sealer.ssm.constant.RoleConstant;
import me.sealer.ssm.controller.dto.CommonResponse;
import me.sealer.ssm.controller.dto.DeleteRoleRequest;
import me.sealer.ssm.controller.dto.NewRoleRequest;
import me.sealer.ssm.model.Role;
import me.sealer.ssm.page.PageResult;
import me.sealer.ssm.service.RoleService;
import me.sealer.ssm.utils.StringUtil;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;

/**
 * @author sealer
 * @date 2016/09/27
 */
@Slf4j
@RestController
@Api(tags = "角色管理相关api")
@RequestMapping("/roleOperations")
@RequiresRoles(RoleConstant.ROLE_ADMIN)
public class RoleController {
    private final RoleService roleService;

    public RoleController(RoleService roleService) {
        this.roleService = roleService;
    }

    @GetMapping("/queryRolesPage")
    @ApiOperation(value = "根据条件分页查询角色列表")
    public CommonResponse<PageResult<Role>> queryRolePage(
            @ApiParam(value = "角色名") @RequestParam(value = Dict.ROLE_NAME, required = false) String roleName,
            @ApiParam(value = "第几页", required = true) @RequestParam(value = PageConstant.PAGE_NO) Integer pageNo,
            @ApiParam(value = "每页记录条数", required = true) @RequestParam(value = PageConstant.PAGE_SIZE) Integer pageSize) {

        if (StringUtil.isNullOrEmpty(roleName)) {
            roleName = null;
        }

        //调用service方法得到角色列表
        PageResult<Role> pageResult = roleService.queryRolesPage(roleName, pageNo, pageSize);
        return new CommonResponse<>(pageResult);
    }

    @ApiOperation(value = "新增角色")
    @PostMapping(value = "/newRole", produces = MediaType.APPLICATION_JSON_VALUE)
    public CommonResponse newRole(@Valid @RequestBody NewRoleRequest newRoleRequest) {

        roleService.newRole(newRoleRequest.getName(), newRoleRequest.getDescription(), newRoleRequest.getPermissions(), newRoleRequest.getMenus());
        return new CommonResponse();
    }

    @ApiOperation(value = "删除角色")
    @PostMapping(value = "/deleteRole", produces = MediaType.APPLICATION_JSON_VALUE)
    public CommonResponse deleteRole(@Valid @RequestBody DeleteRoleRequest deleteRoleRequest) {

        roleService.deleteRole(deleteRoleRequest.getId(), deleteRoleRequest.getName());
        return new CommonResponse();
    }
}
